<template>
  <div>
    展示在线用户：<br>
    <ul>
      <li v-for="i in userlist" :key="i">
        <button @click="chose(i.id)">{{i.name}}</button>
        <!-- {{i.name}} -->

      </li>
    </ul>
    <el-input v-model="msg"></el-input>
    <el-button @click="submit">提交</el-button>

    聊天内容展示：
    <ul>
      <li v-for="i in melist" :key="i">{{i}}</li>
    </ul>

  </div>
</template>

<script>
export default {
  data () {
    return {
      userid: '',
      ws: '',
      msg: '',
      username: '',
      melist: [],
      userlist: [],
      chseid: ''
    }
  },
  methods: {
    imitW () {
      this.userid = this.$route.query.userid
      this.username = '客服' + this.userid
      this.ws = new WebSocket('ws://localhost:8000/ws?userid=' + this.userid + '&name=' + this.username)
      this.ws.onopen = function () {
        alert('success')
      }
      this.ws.onmessage = (msg) => {
        var mes = JSON.parse(msg.data)
        this.melist.push(mes['mes'])
        this.userlist = mes['userlist']
      }
    },
    submit () {
      if (this.chseid) {
        var mes = this.username + '说:' + this.msg
        this.melist.push(mes)
        var sendmes = JSON.stringify({'id': this.chseid, 'mes': mes})

        this.ws.send(sendmes)
      } else {
        alert('必须选择用户')
      }
    },
    chose (id) {
      this.chseid = id
    }
  },
  mounted () {
    this.imitW()
  }

}
</script>

<style>

</style>
